﻿using System;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using ITViet.Web.App_Code;
using ITViet.Services;
using System.Data;
using System.Web;

namespace ITViet.Web.Controls
{
  public partial class TopMenu : BaseControl
	{
		#region Events
		protected void Page_Load(object sender, EventArgs e)
    {
      if (!Page.IsPostBack && !Page.IsCallback)
      {
				Hierarchy = null;
        ShowMenu();
				LoadPageTitle();
      }

      if (Page.IsPostBack)
      {
        if (Request["__EVENTTARGET"] == "FrontMainMenuChange")
        {
          string[] paras = Request["__EVENTARGUMENT"].Split('|');
          if (paras.Length >= 2)
          {
            SelectedSubMenuItem = string.Empty;
            Response.Redirect(paras[1]);
          }
        }
      }
    }

    protected void rptMenu_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
      if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
      HttpContext currentContext = HttpContext.Current;
      string path = Request.Url.AbsolutePath;
      if (currentContext != null && currentContext.Items.Contains("HttpContextRewriteURL") && currentContext.Items["HttpContextRewriteURL"] != null)
      {
        path = currentContext.Items["HttpContextRewriteURL"].ToString();
      }
      string currentPage = path.Substring(path.LastIndexOf('/') + 1);
      DataRowView element = (DataRowView)e.Item.DataItem;
      HtmlControl lnkMenuItem = e.Item.FindControl("lnkMenuItem") as HtmlControl;
      if (lnkMenuItem != null)
      {
        lnkMenuItem.Attributes.Add("onclick", string.Format("javascript:getCurrentMainElement('{0}','{1}')"
                                 , element["Id"] != null ? element["Id"].ToString() : string.Empty
                                 , element["Link"] != null ? element["Link"].ToString() : string.Empty));
        if (element["Pages"] != null && element["Pages"].ToString().Contains("," + currentPage))
        {
					lnkMenuItem.Attributes["class"] = "active";
          SelectedMenuItem = element["Id"].ToString();
          SelectedMenuItemTitle = element["Title"].ToString();
        }
      }
		}
		#endregion

		#region Methods
		private void LoadPageTitle()
		{
			if (Page.Master != null)
			{
				Literal lrPageTitle = Page.Master.FindControl("lrPageTitle") as Literal;
				if (lrPageTitle != null)
				{
					if (string.IsNullOrEmpty(lrPageTitle.Text))
					{
						lrPageTitle.Text = SelectedMenuItemTitle;
					}
				}
			}
		}

		private void ShowMenu()
    {
			SelectedMenuItem = null;
      DataSet listMainMenu = new MainMenuService().GetMainMenuByLanguage(CurrentLanguage.Id, MenuTypes.FrontEnd, null);
      rptMenu.DataSource = listMainMenu;
      rptMenu.DataBind();
		}
		#endregion
	}
}